package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void batchInsertData(IotMsgNotifyData iotMsgNotifyData) {


        // 1.根据iotMsgNotifyData对象获取设备id
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        // 2.根据设备id查询设备信息Device对象
        LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Device::getIotId, deviceId);
        Device device = deviceMapper.selectOne(lambdaQueryWrapper);
        // 3.判断Device对象是否有效，无效则抛出异常结束
        if (Objects.isNull(device)) {
            throw new BaseException("设备不存在");
        }

        // 4.获取iotMsgNotifyData对象里面services集合数据进行遍历每个元对象service
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if (Objects.isNull(properties)) {
                return;
            }
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            // 0.定义List<DeviceData>实例
            ArrayList<DeviceData> deviceDataList = new ArrayList<>();
            properties.forEach((key, value) -> {
                DeviceData deviceData = DeviceData.builder()
                        .iotId(deviceId)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .alarmTime(eventTime)
                        .dataValue(value + "")
                        .build();
                deviceData.setUpdateTime(new Date());
                deviceDataList.add(deviceData);
            });
            // 8.批量插入List<DeviceData>集合数据到数据库中
            saveBatch(deviceDataList);

            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, deviceDataList);
        });
    }
}
